/**
 * 
 */
package com.ailk.evaluation.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author DerekHong
 * 
 */
public class FileUtils {
	static Log log = LogFactory.getLog(FileUtils.class);

	public static final String path = "var/";

	public static void uploadFile(HttpServletRequest request) throws Exception {
		boolean isMultipart = FileUpload.isMultipartContent(request);
		DiskFileUpload upload = new DiskFileUpload();

		List items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		Iterator itr = items.iterator();

		while (itr.hasNext()) {
			FileItem item = (FileItem) itr.next();
			if (item.isFormField()) {
				String name = item.getFieldName();
				String value = null;
				boolean haveValue = false;
				String encoding = null;

				if (item instanceof DiskFileItem) {
					encoding = ((DiskFileItem) item).getCharSet();
					if (log.isDebugEnabled()) {
						log.debug("DiskFileItem.getCharSet=[" + encoding + "]");
					}
				}

				if (encoding == null) {
					encoding = request.getCharacterEncoding();
					if (log.isDebugEnabled()) {
						log.debug("request.getCharacterEncoding=[" + encoding
								+ "]");
					}
				}

				if (encoding != null) {
					try {
						value = item.getString(encoding);
						haveValue = true;
					} catch (Exception e) {
						// Handled below, since haveValue is false.
					}
				}

				if (!haveValue) {
					try {
						value = item.getString("ISO-8859-1");
					} catch (java.io.UnsupportedEncodingException uee) {
						value = item.getString();
					}

					haveValue = true;
				}

				if (haveValue) {
					request.setAttribute(name, value);
				} else {
					String paramValue = request.getParameter(name);
				}

			} else {
				String itemName = ((FileItem)item).getName();
				
				if (StringUtils.isBlank(itemName)) {
					continue;
				}
				
				String fileName ="";
				try
				{
					fileName= new SimpleDateFormat("yyyyMMddhhmmss").format(new Date())+itemName.substring(itemName.lastIndexOf("."));
				}
				catch(Exception ex)
				{
				
				}
				String dirPath = request.getSession().getServletContext()
						.getRealPath("/")
						+ path;
				File dir = new File(dirPath);
				if (!dir.exists()) {
					dir.mkdirs();
				}
				File savedFile = new File(request.getSession()
						.getServletContext().getRealPath("/")
						+ path, fileName);
				try {
					item.write(savedFile);
					request.setAttribute(item.getFieldName(), "/" + path
							+ fileName);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		}
	}

	public static void saveFileContent(String filePath, String fileName, String content,
			boolean isNeedFileExist) {
		if ((isNeedFileExist && isDirExist(filePath, true) && isFileExist(filePath, fileName, true)) || !isNeedFileExist) {
			// write file
			saveFileContent(new File(filePath, fileName), content);
		}
	}

	public static void saveFileContent(File file, String content) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			// byte abyte0[] = content.getBytes();
			byte[] abyte0 = content.getBytes("GBK");
			fos.write(abyte0);
			abyte0 = null;
			content = null;
		} catch (Exception ex) {
			log
					.error("Error occurs when doing method void saveFileContent(filePath,content) from FileUtils.java:\n"
							+ ex.toString());
		} finally {
			try {
				if (fos != null) {
					fos.close();
					fos = null;
				}
			} catch (Exception ex) {
				log
						.error("Error occurs when closing the resource of FileOutputStream from FileUtils.java:\n"
								+ ex.toString());
			}
		}
	}

	public static boolean isDirExist(String Path,
			boolean isCreateIfNotExist) {
		File dir = new File(Path);
		return isCreateIfNotExist ? createDir(dir) : dir.exists();
	}

	private static boolean createDir(File dir) {
		if (!dir.exists()) {
			dir.mkdirs();
		}
		return true;
	}
	
	public static boolean isFileExist(String path, String fileName, boolean isCreateIfNotExist) {
		File file = new File(path, fileName);
		return isCreateIfNotExist ? createFile(file) : file.exists();
		
	}
	
	private static boolean createFile(File file) {
		if (!file.exists()) {
			try {
				return file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return true;
	}

}
